package br.ufc.customJDBC.routing;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import br.ufc.customJDBC.CustomConnection;
import br.ufc.customJDBC.csv.CSVLog;
import br.ufc.parser.Predicate;
import br.ufc.parser.Query;

public class HashRouter implements Router{

	private Collection<CustomConnection> connectionPool;
	private HashMap<Integer, CustomConnection> connectionsID;
	private CSVLog csv;
	
	public HashRouter(Collection<CustomConnection> connectionPool, CSVLog csv) {
		this.connectionPool = connectionPool;
		this.csv = csv;
		this.connectionsID = new HashMap<Integer, CustomConnection>();
		
		int i = 0;
		for (CustomConnection connection : connectionPool) {
			connectionsID.put(i, connection);
			i ++;
		}
	}
	
	private CustomConnection getConnection(String sql){
		Query q;
		try{
			q = new Query(sql);
		}catch(Exception e){
			return connectionsID.get(0);
		}
		HashSet<Predicate> predicates = q.getPredicates();
		Iterator<Predicate> it = predicates.iterator();
		Predicate predicate = it.next();
		int hash = predicate.getValue().hashCode() % 3;
		return connectionsID.get(hash);
	}
	
	@Override
	public boolean execute(String sql) throws SQLException {
		
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public ResultSet executeQuery(String sql) throws SQLException {
		CustomConnection con = getConnection(sql);
		Statement statement = con.createStatement();
		
		long startTime = System.nanoTime();
		ResultSet ret = statement.executeQuery(sql);
		long stopTime = System.nanoTime();
		
		String nodes = "[ " + con.getIp() + " ]";
		csv.writeLine(sql, (stopTime - startTime), 1, "executeQuery", nodes );
		
//		statement.close();
		return ret;
	}

	@Override
	public int executeUpdate(String sql) throws SQLException {
		throw new UnsupportedOperationException("Not supported yet.");
	}
	
}
